/**
 * 微信小程序通过STS直传阿里云OSS
 *（uniapp版上传，小程序原生需要将uni.XXX替换为wx.XXX）
 * 
 * @param {filePath} 图片临时地址
 * @param {option|Object} OSS和STS配置
 * @param {AccessKeySecret} 服务端返回的STS中的AccessKeySecret
 * @param {SecurityToken} 服务端返回的STS中的SecurityToken
 * @param {AccessKeyId} 服务端返回的STS中的AccessKeyId
 * @return {string|boolean} 成功返回文件地址，失败返回false
 */

import crypto from 'crypto-js';
import { Base64 } from 'js-base64';

function upload(filePath,fileType, option = {
    accessKeySecret,
    securityToken,
    accessKeyId,
}, callBack = () => {}) {
    let filename = "chat/" + createFileName() + "." + fileType;
    const date = new Date();
    date.setHours(date.getHours() + 1);
    const policyText = {
        expiration: date.toISOString(), // 设置policy过期时间。
        conditions: [
            ["content-length-range", 0, 10 * 1024 * 1024 * 1024],
        ],
    };
    const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    const signature = computeSignature(option.accessKeySecret, policy)
    const formData = {
        OSSAccessKeyId: option.accessKeyId,
        signature,
        policy,
        'x-oss-security-token': option.securityToken,
        key: filename,
        success_action_status: 200
    }

    let uploadTask = uni.uploadFile({
        url: "https://silkscreen-file.oss-cn-hangzhou.aliyuncs.com",
        filePath: filePath,
        name: "file",
        formData: formData,
        success: (res) => {
            let ossFileName = false;
            if (res.statusCode === 200) {
                ossFileName = filename;
            }
            callBack({code:1,file:ossFileName});
        },
        fail: err => {
            callBack({code:0,err:err});
        }
    })
	uploadTask.onProgressUpdate((res) => {
		callBack({code:2,progress:res.progress});
		// _vm.progressText = res.progress + '%';
		// _vm.percent = res.totalBytesSent + '/' + res.totalBytesExpectedToSend;
	});
}




// 签名
function computeSignature(accessKeySecret, canonicalString) {
    return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

// 生成随机文件名
function createFileName() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}




export default {
    upload
}
